package edu.pw.p2pclient.networking;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import edu.pw.p2pclient.networking.messages.Message;

public class MsgBuffer {
	private boolean mRunning = false;

	BlockingQueue<Message> mItems = new LinkedBlockingQueue<Message>();

	public void start() {
		this.mRunning = true;
	}

	public void put(Message msg) {

		if (!mRunning)
			return;
		try {
			mItems.put(msg);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			// e.printStackTrace();
			mRunning = false;
			mItems.clear();
		}
	}

	public Message take() {

		if (!mRunning)
			return null;
		Message retMsg = null;
		try {
			retMsg = mItems.take();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			// e.printStackTrace();
			mRunning = false;
			mItems.clear();
		}
		return retMsg;
	}

	public void endWork() {

		if (mRunning) {
			mRunning = false;
		}
		mItems.clear();
	}
}
